<template>
  <div v-if="status === 'pending' || status === 'leaving'" class="flex flex-col items-center">
    <div class="text-34px font-bold text-white leading-49px pt-72px pb-29px">
      实付金额：<span class="color-sup">￥{{ backPrice }}</span> 元
    </div>
    <div
      class="w-350px h-390px bg-cover bg-no-repeat flex items-center flex-col"
      :style="{ 'background-image': `url(${payFrame})` }"
    >
      <div class="w-246px h-246px border-secondary mt-52px">
        <QRCodeVue3 v-if="payQrCode" :value="payQrCode" />
      </div>
      <div class="text-18px color-word leading-26px mt-14px">请使用微信扫码支付</div>
    </div>
  </div>
  <div v-if="status === 'success'" class="flex flex-col items-center">
    <div class="mt-158px"><img :src="paySuccess" alt="" /></div>
    <div class="mt-14px leading-49px text-34px font-medium text-white">支付成功</div>
    <div class="color-white-opacity-6 text-18px leading-26px mt-14px opacity-80">
      我们将以最快的速度将商品送到您的手中！
    </div>
    <div
      class="bg-main w-206px h-48px text-center text-white leading-48px text-18px rounded-100px mt-32px cursor-pointer"
      @click="goindex"
    >
      返回首页
    </div>
  </div>
  <div v-if="status === 'leaving'" class="bg-mask-5 fixed w-full h-full left-0 top-0">
    <div
      class="w-356px h-342px absolute left-520px top-226px bg-white rounded-4px flex flex-col items-center"
    >
      <div class="mt-22px"><img :src="payExit" alt="" /></div>
      <div class="mt-10px text-black font-medium text-18px leading-26px">确认离开收银台？</div>
      <div class="mt-14px text-[#999] text-14px leading-20px">
        您的订单还未完成支付，请尽快支付！
      </div>
      <div class="flex items-center mt-28px">
        <div
          class="bg-warn w-104px h-42px text-center leading-42px rounded-68px text-18px font-medium text-white mr-50px cursor-pointer"
          @click="giveuppay"
        >
          确认离开
        </div>
        <div
          class="border-secondary w-104px h-42px text-center leading-42px rounded-68px text-18px font-medium color-secondary cursor-pointer"
          @click="goonpay"
        >
          继续支付
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, unref } from 'vue'
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
import QRCodeVue3 from 'qrcode-vue3'
import payFrame from '@renderer/assets/payFrame.svg'
import { useCartStore } from '@renderer/store/modules/cart'
import useHttp from '@renderer/utils/http'
import paySuccess from '@renderer/assets/paySuccess.svg'
import payExit from '@renderer/assets/payExit.svg'
import { useCategoryStore } from '@renderer/store/modules/category'
import { useContextStore } from '@renderer/store/modules/context'
import { useLocalHttp, transformNo } from '@renderer/utils/http'

const route = useRoute()
const router = useRouter()

const { coupons, total, discount, skuId, minus, giveFee } = route.query

const contextStore = useContextStore()

const destination = ref<any>(null)

const payQrCode = ref<string>('')
// 具体sku的订单id
// const orderNo = ref(route.query.id)
// 批量sku的订单id
const musterOrderId = ref(route.query.musterOrderId)
// 支付来源
const from = ref(route.query.from)
// 支付状态
const status = ref<'pending' | 'success' | 'leaving'>('pending')

const backPrice = ref()

const context = useContextStore()

const cart = useCartStore()
const categoryStore = useCategoryStore()
let timer: number | null = null
const repeatPayResult = async (orders) => {
  timer = setInterval(async () => {
    const { data: res } = await useHttp(`/wx/payResult?order=${unref(musterOrderId)}`)
      .get()
      .json()
    if (res.value.code === 200) {
      clearInterval(timer as number)
      timer = null
      const { data } = await useHttp('/order/success')
        .post({ musterOrderId: unref(musterOrderId) })
        .json()
      if (data.value.code === 200) {
        status.value = 'success'
      }
      Object.keys(orders).forEach((key) => {
        // 本地打印小票
        const order = orders[key]
        if (order.discount) {
          order.price = order.price - order.discount
        }
        order.amount = order.price * order.total
        // order.giveFee = giveFee
        useLocalHttp('/print')
          .post({
            type: 'product',
            no: transformNo(context.no),
            store: context.store_name,
            data: [order]
          })
          .json()
      })
    }
  }, 1000)
}
const giveuppay = () => {
  router.replace(destination.value)
}
const goonpay = () => {
  destination.value = null
  status.value = 'pending'
}
const goindex = () => {
  router.replace({ name: 'Mall' })
}
const generatePayUrl = async (data) => {
  const orders = Object.assign({}, data)
  let name = ''
  let price: any = 0
  data.forEach((d, index) => {
    name += d.name
    if (d.discount) {
      price += Number(d?.price) * Number(d?.total) - (d?.discount || 0)
    } else if (d.minus) {
      price += Number(d?.price) * Number(d?.total)
      if (index === 0) {
        price -= d.minus
      }
    } else {
      price += Number(d?.price) * Number(d?.total)
    }
  })
  // if (data[0]?.discount) {
  //   price = data.reduce((prev, order) => {
  //     prev += Number(order?.price) * Number(order?.total) - (order?.discount || 0)
  //     name += order?.name
  //     return prev
  //   }, 0)
  // } else if (data[0]?.minus) {
  //   price =
  //     data.reduce((prev, order) => {
  //       prev += Number(order?.price) * Number(order?.total)
  //       name += order?.name
  //       return prev
  //     }, 0) - data[0].minus
  // } else {
  //   price = data.reduce((prev, order) => {
  //     prev += Number(order?.price) * Number(order?.total)
  //     name += order?.name
  //     return prev
  //   }, 0)
  // }
  backPrice.value = price
  // 获取数据拼接支付信息
  // 创建订单成功，删除对应的购物车
  if (from.value === 'cart') {
    cart.deleteSelected()
  }
  const { data: res } = await useHttp('/wx/payUrl')
    .post({
      orderNo: unref(musterOrderId),
      amount: backPrice.value,
      name
    })
    .json()
  if (res.value.code === 200) {
    const { code_url, return_code } = res.value.data
    if (return_code === 'SUCCESS') {
      payQrCode.value = code_url
      repeatPayResult(orders)
    }
  }
}
onMounted(async () => {
  if (musterOrderId.value) {
    const { data: res } = await useHttp(
      `/order/c/list?musterOrderId=${musterOrderId.value}&status=1`
    )
      .get()
      .json()
    if (res.value.code === 200) {
      const data = res.value.data
      if (data) {
        await generatePayUrl(data)
      }
    }
  } else if (status.value === 'pending') {
    // 生成订单
    const skus = cart.getSelectedSkus
    const combo = cart.getSelectedComboSkus
    if (skus.length || combo.length) {
      const { data: order } = await useHttp('/order/create')
        .post({
          skus,
          combo,
          store_id: contextStore.store_id,
          no: contextStore.no,
          expired: categoryStore.spu?.expired,
          coupons,
          discount,
          total,
          skuId,
          minus,
          giveFee
        })
        .json()
      if (order.value.code === 200) {
        musterOrderId.value = order.value.data[0]?.muster_order_id
        await generatePayUrl(order.value.data)
      }
    }
  }
})
onUnmounted(() => {
  clearInterval(timer as number)
  timer = null
})
onBeforeRouteLeave(async (to) => {
  if (status.value === 'success' || destination.value) {
    return true
  }
  destination.value = to
  status.value = 'leaving'
  return false
})
</script>

<style scoped></style>
